package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"time"

	"github.com/radovskyb/watcher"
)

func main() {
	dirName, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}
	configs := LoadConfig("./goflush.json")
	fmt.Println("--- "+time.Now().Format("2006-01-02 15:04:05")+" goflush start, dir: "+dirName+", configs:", configs)
	w := watcher.New()
	w.SetMaxEvents(1)
	ignoreDir := configs["ignoreDir"].([]interface{})
	w.Ignore(dirName + "/" + configs["appName"].(string))
	w.Ignore(dirName + "/.git")

	script := `#!/usr/bin/sh
` + dirName + "/" + configs["appName"].(string) + " " + configs["cmd"].(string)

	// 保存到文件
	ioutil.WriteFile(configs["appName"].(string)+`_goflush.sh`, []byte(script), 0766)
	w.Ignore(dirName + "/" + configs["appName"].(string) + "_goflush.sh")
	for _, v := range ignoreDir {
		w.Ignore(dirName + "/" + v.(string))
	}
	go func(dirName, appName, cmd string) {
		for {
			select {
			case event := <-w.Event:
				if !event.FileInfo.IsDir() {
					fmt.Println("--- "+time.Now().Format("2006-01-02 15:04:05"), event)
					go Handle(dirName, appName, cmd)
				}
			case err := <-w.Error:
				log.Fatalln(err)
			case <-w.Closed:
				return
			}
		}
	}(dirName, configs["appName"].(string), configs["cmd"].(string))

	// Watch test_folder recursively for changes.
	if err := w.AddRecursive(dirName); err != nil {
		log.Fatalln(err)
	}

	// Trigger 2 events after watcher started.
	go func() {
		w.Wait()
		w.TriggerEvent(watcher.Create, nil)
		//w.TriggerEvent(watcher.Remove, nil)
	}()

	// Start the watching process - it'll check for changes every 100ms.
	if err := w.Start(time.Millisecond * 100); err != nil {
		log.Fatalln(err)
	}
}
